import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const cartModule = {
  namespaced: true,
  state: {
    list: JSON.parse(localStorage.getItem('cart')) || [],
    order: [],
  },
  getters: {
    allChecked(state) {
      return state.list.every(item => {
        return item.checked
      })
    },
    totalMoney(state) {
      return state.list.reduce((sum, item) => {
        if (item.checked) {
          sum += item.price * item.num
        }
        return sum
      }, 0) * 100
    },
    total(state) {
      return state.list.reduce((sum, item) => {
        sum += item.num
        return sum
      }, 0)
    },
  },
  mutations: {
    addCart(state, payload) {
      const res = state.list.some(item => {
        return item.id === payload.id
      })
      if (res) {
        state.list = state.list.map(item => {
          const copy = { ...item }
          if (copy.id === payload.id) {
            copy.num += payload.num
          }
          return copy
        })
      } else {
        state.list.push({
          ...payload,
          checked: true,
        })
      }
    },
    removeCart(state, payload) {
      state.list = state.list.filter(item => {
        return item.id !== payload.id
      })
    },
    changeCartNum(state, payload) {
      state.list = state.list.map(item => {
        const copy = { ...item }
        if (copy.id === payload.id) {
          copy.num = payload.num
        }
        return copy
      })
    },
    changeChecked(state, payload) {
      state.list = state.list.map(item => {
        const copy = { ...item }
        if (copy.id === payload.id) {
          copy.checked = !copy.checked
        }
        return copy
      })
    },
    changeAllChecked(state, payload) {
      state.list = state.list.map(item => {
        const copy = { ...item }
        copy.checked = payload.checked
        return copy
      })
    },
    addOrder(state, payload) {
      state.order.push(
        ...payload,
      )
    },
    changeOrder(state) {
      state.order = state.order.map(item => {
        const copy = { ...item }
        if (copy.checked) {
          copy.inOrder = true
        }
        return copy
      })
    },
  },
  actions: {
    addCartAsync(context, payload) {
      context.commit('addCart', payload)
    },
  },
}

export default cartModule
